package com.monkey.demolist.tree.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.monkey.demolist.tree.util.TreeHelper;
import com.monkey.demolist.tree.bean.Node;

import java.util.List;

/**
 * Description:
 * Author: Archur
 * Date: 2017-10-20
 * Time: 15:18
 */


public abstract class TreeListViewAdapter<T> extends BaseAdapter {

    protected Context mContext;
    protected List<Node> mAllNodes;
    protected List<Node> mVisibleNodes;

    protected LayoutInflater mInflater;
    protected ListView mTree;

    /**
     * 接口回调
     */
    public interface OnTreeNodeClickListner{
        void onClick(Node node, int position);
    }

    private OnTreeNodeClickListner mListenr;

    public void setOnTreeNodeClickListenr(OnTreeNodeClickListner mListenr) {
        this.mListenr = mListenr;
    }

    public TreeListViewAdapter(ListView tree, Context context, List<T> datas, int defaultExpandLevel) throws IllegalAccessException {
        mContext  = context;
        mAllNodes = TreeHelper.getSortedNodes(datas,defaultExpandLevel);
        mVisibleNodes = TreeHelper.filterVisibleNodes(mAllNodes);
        mInflater = LayoutInflater.from(mContext);

        mTree = tree;
        mTree.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                expandOrCollapse(position);
                if (mListenr != null){
                    mListenr.onClick(mVisibleNodes.get(position),position);
                }
            }
        });
    }

    /**
     * 点击收缩或者展开
     */
    private void expandOrCollapse(int position) {
        Node node = mVisibleNodes.get(position);
        if (node != null){
            if (node.isLeaf()) return;
            node.setExpand(!node.isExpand());
            mVisibleNodes = TreeHelper.filterVisibleNodes(mAllNodes);
            notifyDataSetChanged();
        }
    }

    @Override
    public int getCount() {
        return mVisibleNodes.size();
    }

    @Override
    public Object getItem(int position) {
        return mVisibleNodes.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Node node = mVisibleNodes.get(position);
        convertView = getConverView(node,position,convertView,parent);
        convertView.setPadding(node.getLevel()*30,3,3,3);
        return convertView;
    }

    public abstract View getConverView(Node node,int position, View convertView, ViewGroup parent);
}
